/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package view;

/**
 *
 * @author aeguzkiza
 */

import GUI.JFrameBase;
import javax.swing.text.Position;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;
import libraries.FunctionLibrary;

public class WorklistTreeView {
    PatientPanelView patientPanelView;
    // Declare global variables.
    private Patient patient;
    private Study study;
    private Acquisition acquisition;

    private DefaultMutableTreeNode patientNode;
    private DefaultMutableTreeNode studyNode;
    private DefaultMutableTreeNode acquisitionNode;
    //private String lastPatient = "";
    private int studiesInQueue;
    private final JFrameBase frame;
    private FunctionLibrary LF = new FunctionLibrary();

    public WorklistTreeView(JFrameBase frame) {
        this.frame = frame;
        this.patientPanelView = new PatientPanelView(frame);        
    }

    public void updateViewAddPatient(Integer patientId,String Name,String SurName) {        
        this.studiesInQueue = 0;        
        this.patient = new Patient(Name,SurName,patientId);
        this.patientNode = new DefaultMutableTreeNode(patient);
        LF.addNodeInSortedOrder(frame.topWorklist,patientNode);  // Adds a new Patient in the root node alphabetically sorted.
        //frame.topWorklist.add(patientNode);

        //this.study = new Study(frame.newStudy, null, false);    // New Study censored in worklistTree.
        //this.patientNode.add(new DefaultMutableTreeNode(study));
    }
    
    public void updateViewEditPatient(boolean isNew, String oldName, String oldSurName, Integer patientId, String Name, String SurName) {

        String oldPatientsFullName = oldName+" "+oldSurName;

        if (Name != null || SurName != null ) {
            //if(isNew){updateViewAddPatient(patientId, Name, SurName);}else{  // Add a new Patient node in the JTree.   // New patients can't be created on the worklist.   // Reload must be AFTER the loop to work over this mode.
            if(!isNew){     // Search the node in the tree to change it.
                TreePath path = updateViewSearch(oldPatientsFullName);
                System.out.println("Path: "+path);
                if(path != null){
                    DefaultMutableTreeNode changedNode = (DefaultMutableTreeNode)(MutableTreeNode) path.getLastPathComponent();    // Get's a node by it's path.

                    Patient x = (view.Patient)changedNode.getUserObject();
                    x.setPatientName(Name, SurName);
                }
                frame.model.reload();
            }
        }else{
            System.out.println("The search textField is empty");
        }

    }
    public String updateViewAddStudy(DefaultMutableTreeNode parentNode, Integer studyId, String WorklistDate, int revised) {
        String studyValue = null;
        this.acquisitionNode = null;    // Initializes acquisition variable when a new study is created.
        
        if(revised == 0 && !WorklistDate.isEmpty()){   // When we add a new study from worklistTree that must be writed in the Tree.
        //if(revised == 0 && WorklistDate != null){   // When we add a new study from worklistTree that must be writed in the Tree.
            this.studiesInQueue += 1;
            
            // Create study node:
            this.study = new Study(frame.parseDate(WorklistDate), studyId, true);
            this.studyNode = new DefaultMutableTreeNode(study);
            
            // Add empty acquisition node:
            this.acquisition = new Acquisition(frame.newAcquisition,"", null, true);
            acquisitionNode = new DefaultMutableTreeNode(acquisition);
            this.studyNode.add(acquisitionNode);
            
            // Add study node to its parent:
            if(parentNode == null){
                LF.addNodeInSortedOrder(this.patientNode,studyNode);    // Adds new acquisition study sorted on the last patient.
            }else{
                LF.addNodeInSortedOrder(parentNode,studyNode);  // Adds new study alfabetically sorted on the selected patient.
            }
            studyValue = study.toString();
        }
        return studyValue;
    }
    public void updateViewEditStudy(boolean isNew, String Name, String SurName, String oldWorklistDate, Integer studyId, String WorklistDate){
        // Copied from PatientTreeView
        System.out.println(">>> START OF updateViewEditStudy");
        //String createdStudyName = null; // Catches the name of the new node.
        if (WorklistDate != null ) {
            System.out.println("isNew: "+isNew);
            if(isNew){  // The study couldn't be new if a worklist exists.
                // Select current patient.
                String currentPatientsFullName = Name+" "+SurName;
                TreePath path = updateViewSearch(currentPatientsFullName);

                if(path != null){   // Case of being a Patient, write the study inside its node.
                    DefaultMutableTreeNode changedNode = (DefaultMutableTreeNode)(MutableTreeNode) path.getLastPathComponent(); // Get the node of patient where we want to add a study.
                    updateViewAddStudy(changedNode, studyId, studyDate, WorklistDate, 0);  // Add a new Study node in a patient from JTree.
                }

            }else{  // Change the study node read from DB by a modifyed one.
                TreePath path = updateViewSearch(frame.parseDate(oldWorklistDate)); // Search the old study node.
                System.out.println("oldStudydate: "+frame.parseDate(oldWorklistDate)+" Path: "+path);
                if(path != null){
                    DefaultMutableTreeNode changedNode = (DefaultMutableTreeNode)(MutableTreeNode) path.getLastPathComponent();    // Get's a node by it's path.

                    Study y = (view.Study)changedNode.getUserObject();
                    y.setDate(WorklistDate);
                    y.setWorklist(false);
                    //createdStudyName = y.toString();
                }
            }

            frame.modelPatient.reload();
            //updateViewSearch(createdStudyName); // Selects the last created node.
        }else{
            System.out.println("The search textField is empty");
        }

    }
    //public void updateViewAddAcquisition(Integer acquisitionId,String AcquisitionTime,String AcquisitionName,String ImageLaterality,Integer StudyId) {
    public void updateViewAddAcquisition(DefaultMutableTreeNode parentNode, Integer acquisitionId,String AcquisitionTime,String AcquisitionName,String ImageLaterality,Integer revised) {
    //System.out.println("W0RKLIST acquisitionId:"+acquisitionId+" AcquisitionTime: "+AcquisitionTime+" AcquisitionName: "+AcquisitionName);
    //System.out.println("patientNode: "+patientNode+" studyNode: "+this.studyNode);
        
        //if(this.studyNode != null && this.study.id.equals(StudyId)){ // There's no matched node AND if there is, the node ID is the correct one.
        if(revised == 0 && this.studyNode != null){
            //System.out.println("WORKLIST Current Study ID: "+this.study.id+" ? StudyId: "+StudyId+" Current Study DATE: "+this.study.date);
            // Translation of the eye nomenclature.
            String eye = LF.eyeTranslation(ImageLaterality);
            
            this.acquisition = new Acquisition(eye, frame.parseTime(AcquisitionTime), acquisitionId, true);
            acquisitionNode = new DefaultMutableTreeNode(acquisition);
            if(parentNode == null){
                LF.addNodeInSortedOrder(this.studyNode,acquisitionNode);    // Adds new acquisition alfabetically sorted on the last study.
            }else{
                LF.addNodeInSortedOrder(parentNode,acquisitionNode);        // Adds new acquisition alfabetically sorted on the selected study.
            }
        }
    }
    public void updateViewEditAcquisition(boolean isNew, String currentStudyDate, String study_Id, String oldAquisitionLaterality, String oldAquisitionTime, int acquisition_Id, String ImageLaterality, String AcquisitionTime) {
        System.out.println(">>> START OF updateViewEditAcquisition");

        //String createdStudyName = null; // Catches the name of the new node.
        if (ImageLaterality != null && AcquisitionTime != null) {
            System.out.println("isNew: "+isNew);
            if(isNew){
                // Select current patient.
                TreePath path = updateViewSearch(frame.parseDate(currentStudyDate));

                if(path != null){   // Case of being a Patient, write the study inside its node.
                    DefaultMutableTreeNode changedNode = (DefaultMutableTreeNode)(MutableTreeNode) path.getLastPathComponent(); // Get the node of patient where we want to add an acquisition.
                    updateViewAddAcquisition(changedNode, acquisition_Id, ImageLaterality, AcquisitionTime, 1);  // Add a new Study node in a patient from JTree.
                }

            }else{  // Change the study node read from DB by a modifyed one.
                String oldEye = LF.eyeTranslation(oldAquisitionLaterality);
                TreePath path = updateViewSearch(oldEye+" "+oldAquisitionTime);
                System.out.println("oldAcquisition Laterality+Time: "+oldEye+" "+oldAquisitionTime+" Path: "+path);
                if(path != null){
                    String eye = LF.eyeTranslation(ImageLaterality);
                    DefaultMutableTreeNode changedNode = (DefaultMutableTreeNode)(MutableTreeNode) path.getLastPathComponent();    // Get's a node by it's path.

                    Acquisition z = (view.Acquisition)changedNode.getUserObject();
                    z.setLaterality(eye);
                    z.setTime(oldAquisitionTime);   // Although the acquisition is edited, maintains the acquisitionDate.
                    //createdAcquisitionName = z.toString();
                }
            }

            frame.modelPatient.reload();
            //updateViewSearch(createdAcquisitionName); // Selects the last created node.
        }else{
            System.out.println("The search textField is empty");
        }
    }

    public void updateViewDelete() {
        // Method 1
        TreePath path = null;
        // Find node to remove
        if(frame.WorklistTree.getAnchorSelectionPath() != null){
            path = frame.WorklistTree.getLeadSelectionPath();
        }
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) path.getLastPathComponent();
        //Patient p = (view.Patient)selectedNode.getUserObject();
        //System.out.println("Node deleted from PatientTree "+selectedNode.toString());

        frame.model.removeNodeFromParent(selectedNode);

    }
    public void updateViewRemoveEmptyNode() {
    // Delete Patient nodes without studies.
        if(studiesInQueue == 0){
            frame.topWorklist.remove(patientNode);
        }        
    }
    /*public Integer getPatientId(String PatientsFullName){
        Integer Id = (Integer) patientSelect.get(PatientsFullName);
        return Id;
    }
    public Integer getStudyId(String WorklistDate){
        Integer Id = (Integer) studySelect.get(WorklistDate);
        return Id;
    }*/    
    public TreePath updateViewSearch(String Pattern) {
        TreePath path = null;
        int selectedTab = frame.jTabbedPane2.getSelectedIndex();    // Currently selected tab.
        int startRow = 0;
        
        if(frame.jTabbedPane2.getSelectedIndex() != 0){     // JTabbedPanels start at 0.
            frame.jTabbedPane2.setSelectedIndex(0);         // Works with the worklist tab.
        }       
        path = frame.WorklistTree.getNextMatch(Pattern, startRow, Position.Bias.Forward);
        frame.WorklistTree.setSelectionPath(path);
        frame.jTabbedPane2.setSelectedIndex(selectedTab);   // Returns to the preselected tab.   
        return path;
    }    
}

